/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package quizzempire.view;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.File;
import java.util.Observable;
import java.util.Observer;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import quizzempire.model.IModel;
import quizzempire.model.IQuizz;
import quizzempire.model.statemachine.State;

/**
 *
 * @author Victor
 */
public class StartGame extends javax.swing.JFrame implements Observer{

    /**
     * Creates new form StartGame
     */
    IModel model;
    IQuizz quizz;
    DefaultListModel listModel = new DefaultListModel();
    JRadioButton[] dif = new JRadioButton[3];
    boolean loadFile = false;
    
    
    public StartGame(IModel model) {
        initComponents();
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
        this.model = model;
        lbLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quizzempire/resources/gamerlogo.png")));
        dif[0] = cbEasy;
        dif[1] = cbMedium;
        dif[2] = cbHard;
        
        initFields();
        
        model.addObserver(this);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        difficultyGroup = new javax.swing.ButtonGroup();
        DIFFICULTY = new java.awt.Label();
        jScrollPane1 = new javax.swing.JScrollPane();
        quizzList = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        lbGenre = new javax.swing.JLabel();
        lbQuizBy = new javax.swing.JLabel();
        lbQuizDescription = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        taDescription = new javax.swing.JTextArea();
        lbName = new javax.swing.JLabel();
        btStartGame = new javax.swing.JButton();
        btMainMenu = new javax.swing.JButton();
        btLoadQuiz = new javax.swing.JButton();
        lbLogo = new javax.swing.JLabel();
        cbEasy = new javax.swing.JRadioButton();
        cbMedium = new javax.swing.JRadioButton();
        cbHard = new javax.swing.JRadioButton();

        javax.swing.GroupLayout jLayeredPane1Layout = new javax.swing.GroupLayout(jLayeredPane1);
        jLayeredPane1.setLayout(jLayeredPane1Layout);
        jLayeredPane1Layout.setHorizontalGroup(
            jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jLayeredPane1Layout.setVerticalGroup(
            jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setFont(new java.awt.Font("Aharoni", 0, 14)); // NOI18N

        DIFFICULTY.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        DIFFICULTY.setText("DIFFICULTY");

        quizzList.setModel(listModel);
        quizzList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                quizzListMouseClicked(evt);
            }
        });
        quizzList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                quizzListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(quizzList);

        jPanel1.setBackground(new java.awt.Color(204, 204, 204));

        lbGenre.setText("Genre:");

        lbQuizBy.setText("Creator:");

        lbQuizDescription.setText("Description: ");

        taDescription.setEditable(false);
        taDescription.setBackground(new java.awt.Color(204, 204, 204));
        taDescription.setColumns(20);
        taDescription.setLineWrap(true);
        taDescription.setRows(4);
        taDescription.setBorder(null);
        jScrollPane2.setViewportView(taDescription);

        lbName.setText("Name:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lbGenre)
                        .addContainerGap(216, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lbQuizDescription)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbName)
                            .addComponent(lbQuizBy))
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(7, 7, 7)
                .addComponent(lbName)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbGenre)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lbQuizBy)
                .addGap(31, 31, 31)
                .addComponent(lbQuizDescription)
                .addContainerGap(37, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        btStartGame.setText("START GAME");
        btStartGame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btStartGameActionPerformed(evt);
            }
        });

        btMainMenu.setText("MAIN MENU");
        btMainMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btMainMenuActionPerformed(evt);
            }
        });

        btLoadQuiz.setText("LOAD");
        btLoadQuiz.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLoadQuizActionPerformed(evt);
            }
        });

        lbLogo.setText("LOGO");

        difficultyGroup.add(cbEasy);
        cbEasy.setText("Easy");

        difficultyGroup.add(cbMedium);
        cbMedium.setText("Medium");

        difficultyGroup.add(cbHard);
        cbHard.setText("Hard");
        cbHard.setToolTipText("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btMainMenu, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btLoadQuiz)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btStartGame, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(DIFFICULTY, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cbEasy)
                            .addComponent(cbMedium)
                            .addComponent(cbHard))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(lbLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(13, 13, 13))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addComponent(DIFFICULTY, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cbEasy)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cbMedium)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cbHard)
                        .addGap(18, 18, 18)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(9, 9, 9)
                        .addComponent(btLoadQuiz))
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btStartGame, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btMainMenu, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btLoadQuizActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLoadQuizActionPerformed
        
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File(model.getQuizzesFolder()));
        int retrival = chooser.showOpenDialog(this);
        if (retrival == JFileChooser.APPROVE_OPTION)
        {
            int x = model.loadQuizz(chooser.getSelectedFile().getAbsolutePath());
            if (x == -1)
                JOptionPane.showMessageDialog(this, "The loaded file is not a quizz", "Invalid Quizz", JOptionPane.ERROR_MESSAGE);
            if (x == -2)
                JOptionPane.showMessageDialog(this, "The loaded file is already loaded", "Quizz is loaded", JOptionPane.ERROR_MESSAGE);
        }

        
    }//GEN-LAST:event_btLoadQuizActionPerformed

    private void btMainMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btMainMenuActionPerformed
        model.restart();
    }//GEN-LAST:event_btMainMenuActionPerformed

    private void btStartGameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btStartGameActionPerformed
        if(quizzList.getSelectedIndex() == -1)
            return;
        int d = -1;
        for(int i = 0; i< 3; i++)
        {
            if (dif[i].isSelected())
            {
                d=i;
                break;
            }
        }
        if (d == -1) return;
        model.startGame(quizzList.getSelectedIndex(), d);
    }//GEN-LAST:event_btStartGameActionPerformed

    private void quizzListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_quizzListMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_quizzListMouseClicked

    private void quizzListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_quizzListValueChanged
        if (evt.getValueIsAdjusting())
            return;
        
        if (quizzList.getSelectedIndex() != -1)
        {
            quizz = model.getQuizzInfo(quizzList.getSelectedIndex());
            if (quizz == null)
            {
                JOptionPane.showMessageDialog(this, "Error on loading quizz from file", "Error reading file", JOptionPane.ERROR_MESSAGE);
                quizz = null;
                return;
            }
            
            updateQuizzInfo();              
        }
        else
            quizz = null;
    }//GEN-LAST:event_quizzListValueChanged



    public void update(Observable o , Object arg){
        State state = model.getState(); 
        if (!(state instanceof quizzempire.model.statemachine.PrepareGame))
        {
            model.deleteObserver(this);
            MainBuilder.changeScreen(this, model, state);
        }
        else
        {
            updateList();
            updateQuizzInfo();
        }
    } 
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.awt.Label DIFFICULTY;
    private javax.swing.JButton btLoadQuiz;
    private javax.swing.JButton btMainMenu;
    private javax.swing.JButton btStartGame;
    private javax.swing.JRadioButton cbEasy;
    private javax.swing.JRadioButton cbHard;
    private javax.swing.JRadioButton cbMedium;
    private javax.swing.ButtonGroup difficultyGroup;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lbGenre;
    private javax.swing.JLabel lbLogo;
    private javax.swing.JLabel lbName;
    private javax.swing.JLabel lbQuizBy;
    private javax.swing.JLabel lbQuizDescription;
    private javax.swing.JList quizzList;
    private javax.swing.JTextArea taDescription;
    // End of variables declaration//GEN-END:variables

    private void initFields() {
        
        updateList();
            
    }

    private void updateList() {
        listModel.clear();
        String[] list = model.getQuizzList();
        for (int i = 0; i < list.length; i++)
            listModel.addElement(list[i]);
    }

    private void updateQuizzInfo() {
        if (quizz == null)
            return;
        
        lbName.setText("Name: "+quizz.getName());
        lbGenre.setText("Genre: "+quizz.getGenre());
        lbQuizBy.setText("Creator: "+quizz.getAuthor());
        taDescription.setText(quizz.getDescription());
        boolean [] available = quizz.getDifAvailable();
        boolean encontrado = false;
        for (int i = 0; i < 3; i++)
        {
            dif[i].setEnabled(available[i]);
            if (!encontrado && available[i])
                dif[i].setSelected(true); 
        }
    }
}
